package com.huping.utils;

import lombok.Getter;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JavaComplier extends MyCompiler {
    Runtime run;
    private String javaPath = "/home/clear/software/java/jdk-21_linux-x64_bin/jdk-21.0.1/bin";
    private InputStream errorStream;
    @Getter
    private List<String> inputResult;
    @Getter
    private String errorResult="";

    public JavaComplier() {
        this.inputResult = new ArrayList<>();
    }

    public int start(String code,List<String> inputCases) throws IOException, InterruptedException {
        //初始化
        run=Runtime.getRuntime();
        //创建文件
        FileWriter fileWriter = new FileWriter("Solution.java");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(code);
        bufferedWriter.close();
        fileWriter.close();
        //编译代码
        Process process = run.exec(javaPath+"/javac "+"Solution.java");
        process.waitFor();
        errorStream = process.getErrorStream();
        BufferedReader bfError = new BufferedReader(new InputStreamReader(errorStream));
        String read=null;
        while ((read = bfError.readLine()) != null) {
            errorResult=errorResult+read+"\n";
        }
        if(!errorResult.isEmpty()){
            return 1;
        }
        //执行代码
        for (String inputCase : inputCases) {
            process = run.exec(javaPath+"/java "+"Solution");
            OutputStream outputStream = process.getOutputStream();
            InputStream inputStream = process.getInputStream();
            outputStream.write(inputCase.getBytes());
            outputStream.flush();
            outputStream.close();

            long startTime = System.currentTimeMillis();
            boolean processFinished = false;
            while(System.currentTimeMillis()-startTime < 4*1000
                    && !processFinished ){
                try {
                    int exitVal = process.exitValue();
                } catch (IllegalThreadStateException e) {
                    Thread.sleep(200);
                    continue;
                }
                processFinished = true;
            }

            String resultTemp="";
            if (processFinished){
                BufferedReader bfInput = new BufferedReader(new InputStreamReader(inputStream));
                while ((read = bfInput.readLine()) != null) {
//                System.out.println("job result [" + read + "]");
                    resultTemp=resultTemp+"\n"+read;
                }
            }else{
                resultTemp="timeout";
            }

            inputResult.add(resultTemp);
        }
        //删除文件
        process = run.exec("rm Solution.java Solution.class");
        process.waitFor();
        return 0;
    }

}
